const coBody = require('co-body');
const { getList, addData, deleteData } = require("../utils/list");

const errorList = require("../database/error.json").data
const recordScreenList = require("../database/recordScreen.json").data
const performanceList = require("../database/performance.json").data

let prefix = "/monitor";

function createRoute(app, root_prefix) {
	prefix = root_prefix + prefix

  app.get(`${prefix}/getErrorList`, (req, res) => {
    const data = getList(errorList, req.query);
    res.send({
      code: 200,
      data,
    });
  });

  app.get(`${prefix}/getRecordScreenId`, (req, res) => {
    let id = req.query.id;
    let data = recordScreenList.filter(
      (item) => item.recordScreenId == id
    );
    res.send({
      code: 200,
      data,
    });
  });

  app.post(`${prefix}/reportData`, async (req, res) => {
    try {
      // req.body 不为空时为正常请求，如录屏信息
      let length = Object.keys(req.body).length;
      if (length) {
        addData(recordScreenList, req.body);
      } else {
        // 使用 web beacon 上报数据
        let data = await coBody.json(req);
        if (!data) return;
        if (data.type == "performance") {
          addData(performanceList, data);
        } else if (data.type == "recordScreen") {
          addData(recordScreenList, data);
        } else if (data.type == "whiteScreen") {
        } else {
          addData(errorList, data);
        }
      }
      res.send({
        code: 200,
        message: "上报成功！",
      });
    } catch (err) {
      res.send({
        code: 203,
        message: "上报失败！",
        err,
      });
    }
  });

  app.delete(`${prefix}/error-item/:id`, async (req, res) => {
    let { id } = req.params;
    if (!id) {
      res.send({
        code: 405,
        message: "fail",
      });
    } else {
      await deleteData(errorList, Number(id));
      res.send({
        code: 200,
        message: "success",
      });
    }
  });

  app.delete(`${prefix}/screen-item/:id`, async (req, res) => {
    let { id } = req.params;
    if (!id) {
      res.send({
        code: 405,
        message: "fail",
      });
    } else {
      await deleteData(performanceList, id, (key = "recordScreenId"));
      res.send({
        code: 200,
        message: "success",
      });
    }
  });
}

module.exports = createRoute;
